<template>
	<div class="containers">
		<div class="container">
			<div class="handle-box">
				<el-button type="primary" icon="el-icon-plus" class="handle-add mr10"  size="small" @click="addregion">添加</el-button>
				<!-- <el-select v-model="code" @change="getData()" placeholder="请选择类型" size="small">
					<el-option v-for="(item, index) in options" :key="item.id" :label="item.key" :value="index">
					</el-option>
				</el-select> -->
			</div>

			<el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header"
				@selection-change="handleSelectionChange" v-loading="loading">
				<el-table-column label="类型" align="center">
					<template slot-scope="scope">
						<div v-for="item in options" v-if="item.id==scope.row.code">
							{{ item.key }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="title" label="标题">
				</el-table-column>
				<el-table-column prop="message" label="模版内容"></el-table-column>
				<el-table-column label="是否启用" align="center">
					<template slot-scope="scope">
						<el-tag :type="scope.row.is_use ? 'success' : 'danger'">{{
							scope.row.is_use ? '是' : '否' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" align="center">
					<template slot-scope="scope">
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button type="text" icon="el-icon-delete" class="red"
							@click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
					:page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
			</div>
		</div>

		<!-- 编辑/添加弹出框 -->
		<el-dialog :title="type?'编辑':'添加'" :visible.sync="editVisible" width="30%">
			<el-form ref="form" :model="form" label-width="70px">
				<el-form-item label="类型">
					<el-select v-model="form.code" placeholder="请选择类型">
						<el-option v-for="(item, index) in options" :key="item.id" :label="item.key" :value="index">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="标题"><el-input v-model="form.title" ></el-input></el-form-item>
				<el-form-item label="模版内容">
          <textarea v-model="form.message" id="message" style="width: 100%;min-height: 70px;" @input="handleInputChange"></textarea>
          <div class="spanList">点击变量添加到光标处: <br>
            用户:<span @click="insertInputTxt('message','${user}')">${user}</span> -
            来源:<span @click="insertInputTxt('message','${source}')">${source}</span> -
            订单号:<span @click="insertInputTxt('message','${order}')">${order}</span> -
            钱:<span @click="insertInputTxt('message','${money}')">${money}</span></div>
        </el-form-item>
				<el-form-item label="是否启用">
						<el-switch :active-value="1" :inactive-value="0" v-model="form.is_use"></el-switch>
					</el-form-item>

			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="saveEdit">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	name: 'basetable',
	data() {
		return {
			options: [
        {key:'下单成功',id:0},
        {key:'发货成功',id:1},
        {key:'确认收货',id:2},
        {key:'订单取消',id:3},
        {key:'订单完成',id:4},
        {key:'获得积分',id:5},
        {key:'提现成功',id:6},
        {key:'退款成功',id:7},
        // {key:'新增VIP会员',id:10},
        // {key:'用户下单提醒发货',id:11},
        // {key:'订单完成',id:12},
        // {key:'货款解冻',id:13},
        // {key:'提现成功',id:14},
        // 用户：.
        // 0 确认收货
        // 1 下单成功
        // 2 直推奖励
        // 3 提现成功
        // 4 获得积分
        // 5 会员套餐升级VIP  云店：
        // 6 用户下单提醒发货
        // 7 订单完成
        // 8 货款解冻
        // 9 提现成功
        // 10 新增VIP会员 供应商：
        // 11 用户下单提醒发货
        // 12 订单完成
        // 13 货款解冻
        // 14 提现成功
      ], // 下拉选项
			form: {
				message: '',
				title: "",
				is_use:1,
				code:0
			},
			query: {
				pageIndex: 1,
				 pageSize: 20
			},
			upimg: {
				token: '',
				key: new Date().valueOf()
			},
			code:0,
			upload:'',
			url:'',
			tableData: [],
			multipleSelection: [],
			editVisible: false,
			pageTotal: 0,
			imageUrl: '',
			type:0,
			loading:false,
      defaultValues: { // 默认值
        user: '',
        email: '' ,
        order: '',
        money: '',
      }
		};
	},
	created() {
		this.getToken().then(res => {
      this.upimg.token = res.data.token
      this.url = res.data.url
      this.upload = res.data.upload
    },
      function () {
        console.log('请求失败处理');
      }
    )
		this.getData()
	},
	methods: {
    handleInputChange(e) {
      console.log(e.target.value)
      // 定义一个包含所有模板变量格式的正则表达式
      const templateRegex = /\$\{([^}]+)\}/g;
      let match;
      let processedStr =e.target.value

      // 找到所有匹配的模板变量并处理它们
      while ((match = templateRegex.exec(processedStr)) !== null) {
        const variableName = match[1]; // 捕获变量名，如 'user' 或 'email'

        // 检查默认值对象中是否有这个变量名
        if (this.defaultValues.hasOwnProperty(variableName)) {
          // 检查模板变量是否完整（即没有被部分删除或修改）
          if (!new RegExp(`^\\$\{${variableName}\\}$`).test(match[0])) {
            // 如果不完整，用默认值替换整个模板变量
            processedStr = processedStr.replace(match[0], this.defaultValues[variableName]);
          }
        } else {
          // 如果默认值对象中没有这个变量名，你可以选择移除它或保留它
          // 这里我们选择移除它
          processedStr = processedStr.replace(match[0], '');
        }
      }

      // 更新处理后的值
      this.form.message = processedStr;
    },
     insertInputTxt(id, insertTxt){
      var elInput =document.getElementById(id);
      var startPos = elInput.selectionStart;
      var endPos = elInput.selectionEnd;
      if(startPos ===undefined|| endPos ===undefined)return
      var txt = elInput.value;
      var result = txt.substring(0, startPos) + insertTxt + txt.substring(endPos)
      // elInput.value = result;
      // elInput.focus();
      // this.$nextTick(() => {
      //       elInput.selectionStart = startPos + insertTxt.length;
      //   elInput.selectionEnd = startPos + insertTxt.length;
      //     })
         this.form.message=result
    },
		// 上传图片
		handleAvatarSuccess(res, file) {
			this.form.img = this.url + res.key;
			this.imageUrl = URL.createObjectURL(file.raw);
		},
		beforeupload(file) {
			if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
				this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
				return false;
			}
			// if (file.size / 1024 / 1024 > 1) {
			// 	this.$message.error('上传图标大小不能超过 1M!');
			// 	return false;
			// }
			let types = file.name.split('.')//获取图片格式
			this.upimg.key = this.$template+'/home/' + new Date().valueOf() + '.' + types[types.length-1];
		},
		//获取数据
		getData() {
      	this.loading=true
			this.request('admin/messageTemplate/', 'get', { page: this.query.pageIndex, size: this.query.pageSize,code:this.code }).then(res => {
				console.log(res)
				this.tableData=res.data.data
				this.pageTotal=res.data.total
      	this.loading=false
			})
		},
		// 编辑
		handleEdit(e) {
			this.editVisible = true;
			this.form = e;
			this.imageUrl = e.img;
			this.type=1
		},
		cancel() {
			this.editVisible = false;
			this.form = {
				message: '',
				title: "",
				is_use:1,
				code:0
			};
			this.getData();
		},
		// 修改排序
		operations(e, code) {
			console.log(e)
			this.request('admin/messageTemplate/', 'put',e).then(res => {
				if (res.errno == 0) {
					this.$message.success(res.errmsg);
					this.getData()
				} else {
					this.$message.error(res.errmsg);
				}
			this.editVisible = false;
			this.getData();
			});
		},
		// 删除操作
		handleDelete(index, row) {
			// 二次确认删除
			this.$confirm('确定要删除吗？', '提示', {
				type: 'warning'
			})
				.then(() => {
					this.request('admin/messageTemplate/', 'delete', { id: row.ID }).then(res => {
						if (res.errno == 0) {
							this.$message.success(res.errmsg);
							this.tableData.splice(index, 1)
							this.getData()
						} else {
							this.$message.error(res.errmsg);
						}
					});
				})
		},
		// 多选操作
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 添加
		addregion() {
			this.form = {
				message: '',
				title: "",
				is_use:1,
				code:0
			};
			this.type=0
			this.imageUrl = '';
			this.editVisible = true;
		},

		// 添加/修改
		saveEdit() {
      // if (!this.form.url) return this.$message.error('请输入跳转地址');
      // if (!this.form.img) return this.$message.error('请上传图片');
			// this.form.title=Number(this.form.title)
			this.request('admin/messageTemplate/', this.type?'put':'post', this.form).then(res => {
				if (res.errno == 0) {
					this.$message.success(res.errmsg);
					this.form = {
            message: '',
				title: "",
				is_use:1,
				code:0
						};
				} else {
					this.$message.error(res.errmsg);
				}
			this.editVisible = false;
			this.getData();
			});
		},
		// 分页导航
		handlePageChange(val) {
			this.$set(this.query, 'pageIndex', val);
			this.getData();
		}
	}
};
</script>

<style scoped>
.container {
	padding: 20px;
}
.el-upload--text {
	width: 200px !important;
}

.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;

	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	/* width: 100px; */
	height: 100px;
	line-height: 100px;
	text-align: center;
}

.avatar {
	width: 100%;
	height: 178px;
	display: block;
}

.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
	display: inline-block;
}

.table {
	width: 100%;
	font-size: 14px;
}

.red {
	color: #ff0000;
}

.mr10 {
	margin-right: 10px;
}

.table-td-thumb {
	display: block;
	margin: auto;
	width: 200px;
	height: 60px;
	.el-image img{
		object-fit: cover;
	}
}
/* 设置分页按钮样式 */
.pagination{
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
}
.spanList span{
  color: #409eff;
  &:hover {
        cursor: pointer;
    }
}
</style>
